import { useEffect, useMemo, useState } from 'react';
import { IS_BROWSER } from '../utils/detect';

function useWindowSize() {
	const [width, setWidth] = useState(() =>
		IS_BROWSER ? window.innerWidth : 0,
	);
	const [height, setHeight] = useState(() =>
		IS_BROWSER ? window.innerHeight : 0,
	);

	useEffect(() => {
		if (!IS_BROWSER) {
			return;
		}

		const onResize = () => {
			setWidth(window.innerWidth);
			setHeight(window.innerHeight);
		};

		window.addEventListener('resize', onResize);
		window.addEventListener('orientationchange', onResize);

		return () => {
			window.removeEventListener('resize', onResize);
			window.removeEventListener('orientationchange', onResize);
		};
	}, []);

	return useMemo(() => ({ width, height }), [width, height]);
}

export default useWindowSize;
